<?php
// $Id$

/**
 * Controller_Admin_Productcard 控制器
 */
class Controller_Admin_Productcard extends Controller_Abstract
{

	function actionIndex()
	{
		// 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
	}
	function actionsearch()
	{
	}
	function actiondel()
	{
		$this->union_table = Productcard::meta();
		$this->delete(array('id'=>$this->_context->ids));
	}
	
	function actionlist()
	{
		$this->union_table = Productcard::meta();
		$this->lists();
	}

	function actionimport()
	{
		$p_code = isset($this->_context->p_code)?trim($this->_context->p_code):null;
		if (is_null($p_code))
		{
			return $this->error('参数不正确');
		}else
		{
			$product = Product::find('p_code = ?',$p_code)->getOne();
			if (!$product->id())
			{
				return $this->error('不存在'.$p_code.' 的充值卡产品');
			}
		}
		if ($this->_context->isGET())
		{
			$form = new Form_cardupload(url('admin::productcard/import'));
			$form->import(array('p_code'=>$p_code));
			$this->_view['form'] = $form;

		}else if ($this->_context->isPOST())
		{
			$cardfile = isset($this->_context->cardfile)?trim($this->_context->cardfile):'';
			if (is_file($cardfile))
			{
				$des = $this->_context->des;
				$handle = fopen($cardfile, 'r');
				$split_char = ',';
				if ($handle)
				{
					$i = 0;
					$line_num = 0;
					$err_line = '';
					while (!feof($handle))
					{
						$line_num += 1;
						$lineCard = fgets($handle,400);
						$Split_arr = explode($split_char, $lineCard);
						if(count($Split_arr)>=2 )
						{
							if(strlen($Split_arr[0])>1 && strlen($Split_arr[1])>1)
							{
								$card = array(
								'code'=>trim($Split_arr[0]),
								'pass'=>trim($Split_arr[1]),
								'p_code'=>$p_code,
								'createtime'=>time(),
								'des'=>$des
								);
								$has_one = Productcard::find('code = ? and pass = ?',$card['code'],$card['pass'])->getOne();
								if (!$has_one->id())
								{
									//存入数据
									QDB::getConn()->startTrans();
									try {
										$i += 1;
										$card_obj = new Productcard($card);
										$card_obj->save(0,'create');
										QDB::getConn()->completeTrans(true);
									} catch (Exception $e) {
										$err_line .= $line_num+',';
										QDB::getConn()->completeTrans(FALSE);
										continue;
									}
								}else
								{
									$err_line .= $line_num + ',';
									//存在
									continue;
								}
									
							}else {
								//卡密长度小于1
								$err_line .= $line_num + ',';
								continue;
							}
						}else
						{
							$err_line .= $line_num + ',';
							//数组长度不对
							continue;
						}
					}
					//
					fclose($handle);
					//删除文件
					@unlink($cardfile);
					return $this->success("成功 {$i}条,失败存在于:{$err_line}行");
				}else
				{
					return $this->error('文件打开失败');
				}
			}else
			{
				return $this->error('文件不存在');
			}

		}
	}
}


